package gov.pbc.nn.kjgl.task.handler;

import gov.pbc.nn.kjgl.task.entity.TaskBranchUser;
import gov.pbc.nn.kjgl.task.entity.TaskEntity;
import gov.pbc.nn.kjgl.task.entity.TaskProcessor;
import gov.pbc.nn.kjgl.task.view.TaskPR;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Component;

import com.bstek.bdf2.core.context.ContextHolder;
import com.bstek.uflo.env.Context;
import com.bstek.uflo.model.HistoryProcessInstance;
import com.bstek.uflo.model.ProcessInstance;
import com.bstek.uflo.process.handler.ProcessEventHandler;

@Component(TaskProcessEventHandler.BEAN_ID)
public class TaskProcessEventHandler implements ProcessEventHandler {

	public static final String BEAN_ID = "gov.pbc.nn.kjgl.task.handler.TaskProcessEventHandler";

	@Override
	public void end(ProcessInstance arg0, Context arg1) {

	}

	@Override
	public void start(ProcessInstance pi, Context context) {
		long pId = pi.getParentId();
		if (pId == 0) {
			return;
		}
		String chuzhang = (String) context.getProcessService().getProcessVariable("taskEntityChuzhang", pId);
		TaskEntity task = (TaskEntity) context.getProcessService().getProcessVariable("taskEntity", pId);
		if (task != null) {
			Map<String, Object> variables = new HashMap<String, Object>();
			pi.setBusinessId(task.getId());
			pi.setPromoter(ContextHolder.getLoginUserName());
			String taskEntityId = task.getId();
			boolean needBranch = task.getNeedBranch();
			boolean driectProcessor = task.getDriectProcessor();

			if (StringUtils.isNoneBlank(chuzhang)) {
				variables.put("chuzhang", chuzhang);
			}
			variables.put("shouldCz", task.getShouldCz());
			variables.put("driectProcessor", driectProcessor);
			variables.put("needBranch", needBranch);

			TaskPR taskPr = ContextHolder.getApplicationContext().getBean(TaskPR.class);
			if (driectProcessor) {
				Collection<TaskProcessor> processors;
				try {
					processors = taskPr.getProcessorsbyTaskId(taskEntityId);
				} catch (Exception e) {
					throw new RuntimeException(e);
				}
				List<String> processorList = new ArrayList<String>();
				for (TaskProcessor taskProcessor : processors) {
					processorList.add(taskProcessor.getUsername());
				}
				variables.put("processorList", processorList);
			}
			variables.put("agree", 1);
			context.getProcessService().saveProcessVariables(pi.getId(), variables);
			context.getSession().saveOrUpdate(pi);

			HistoryProcessInstance hpi = (HistoryProcessInstance) context.getSession()
					.createCriteria(HistoryProcessInstance.class).add(Restrictions.eq("processInstanceId", pi.getId()))
					.uniqueResult();
			hpi.setBusinessId(pi.getBusinessId());
			hpi.setPromoter(pi.getPromoter());
			context.getSession().update(hpi);
		}
	}
}
